package com.example.administrator.im.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.administrator.im.MyApplication;
import com.example.administrator.im.R;
import com.example.administrator.im.adapter.Linkman_List_Adapter;
import com.example.administrator.im.config.PhoneParam;
import com.example.administrator.im.data.LinkmanListData;
import com.example.administrator.im.db.FriendDBHelper;
import com.example.administrator.im.db.GroupDBHelper;
import com.example.administrator.im.interfacz.ShareTitleable;
import com.example.administrator.im.json.FriendJson;
import com.example.administrator.im.json.ResultJson;
import com.example.administrator.im.ui.activity.FriendDetailsActivity;
import com.example.administrator.im.ui.activity.HomeActivity;
import com.example.administrator.im.ui.activity.LinkmanManageActivity;
import com.example.administrator.im.ui.activity.SearchFriendActivity;
import com.example.administrator.im.ui.activity.SystemNotifycationActivity;
import com.example.administrator.im.utils.HttpUtils;
import com.example.administrator.im.view.ShareTitle;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static java.lang.Thread.sleep;

/**
 * create:2018/9/14 22:18
 * author: 姚鸿杰
 **/
public class LinkmanFragment extends Fragment implements View.OnClickListener {

    private final String TAG = "LinkmanFragment";

    private ShareTitle shareTitle;

    private LinearLayout seek;

    private ExpandableListView elv;
    private Linkman_List_Adapter adapter;

    private LinearLayout add_friend;
    private LinearLayout create_group;
    private RelativeLayout systen_msg;

    private ImageView system_hint;

    private String[] groups = new String[0];
    private LinkmanListData[][] childs = new LinkmanListData[0][0];

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            adapter.setData(groups, childs);
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_linkman, container, false);

        initView(v);

        adapter = new Linkman_List_Adapter(groups, childs, MyApplication.getmContext());
        elv.setAdapter(adapter);
        elv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                Intent intent = new Intent(getContext(), FriendDetailsActivity.class);
                //传递参数
                LinkmanListData data = (LinkmanListData) adapter.getChild(groupPosition, childPosition);
                intent.putExtra("username", data.getUsername());
                intent.putExtra("nickname", data.getNickname());
                getActivity().startActivity(intent);
                return true;
            }
        });
        EventBus.getDefault().register(this);

        return v;
    }

    private void initView(View v) {
        system_hint = (ImageView) v.findViewById(R.id.system_hint);
        add_friend = (LinearLayout) v.findViewById(R.id.linkman_friend);
        create_group = (LinearLayout) v.findViewById(R.id.linkman_group);
        systen_msg = (RelativeLayout) v.findViewById(R.id.linkman_system_msg);
        add_friend.setOnClickListener(this);
        create_group.setOnClickListener(this);
        systen_msg.setOnClickListener(this);

        elv = (ExpandableListView) v.findViewById(R.id.linkman_elv);

        seek = (LinearLayout) v.findViewById(R.id.seek);
        seek.setOnClickListener(this);

        shareTitle = (ShareTitle) v.findViewById(R.id.linkman_toolbar);
        ViewGroup.LayoutParams lp = shareTitle.getLayoutParams();
        ((ViewGroup.MarginLayoutParams) lp).setMargins(0, PhoneParam.getInstance(getContext()).getStatus_height(), 0, 0);
        shareTitle.setLayoutParams(lp);
        shareTitle.setIconOnClickListener(new ShareTitleable() {
            @Override
            public void left_click(View v) {
            }

            @Override
            public void right_click(View v) {
                getActivity().startActivity(new Intent(getActivity(), LinkmanManageActivity.class));
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        initExpandable();
    }


    //初始化二级列表
    private void initExpandable() {
        //从数据库获取分组并按分组序号升序排序
        final List<GroupDBHelper> groupDBHelperList = LitePal.order("position asc").find(GroupDBHelper.class);
        //如果分组存在
        if (groupDBHelperList.size() != 0) {

            List<FriendDBHelper> friends = LitePal.findAll(FriendDBHelper.class);

            if (HomeActivity.isIsSearchFriend() || friends.size() != 0) {
                initData(groupDBHelperList);
                Message msg = new Message();
                handler.sendMessage(msg);
            } else {
                reInit();
            }


        } else {
            reInit();
        }
    }

    private void reInit() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    sleep(500);
                    initExpandable();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //初始化数据
    private void initData(List<GroupDBHelper> groupDBHelperList) {
        //动态分配分组大小
        int size = groupDBHelperList.size();
        groups = new String[size];
        childs = new LinkmanListData[size][];

        for (int i = 0; i < size; i++) {

            GroupDBHelper group = groupDBHelperList.get(i);
            groups[i] = group.getName();
            //获取该分组的好友
            List<FriendDBHelper> friends = group.getFriends();
            int count = friends.size();
            childs[i] = new LinkmanListData[count];

            for (int j = 0; j < count; j++) {
                String username = friends.get(j).getUsername();
                String nickname = TextUtils.isEmpty(friends.get(j).getRemarks()) ?
                        friends.get(j).getNickname() : friends.get(j).getRemarks();
                String url = HttpUtils.PORT + friends.get(j).getImg_path();
                LinkmanListData data = new LinkmanListData(username, nickname, url);
                childs[i][j] = data;
            }
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.e(TAG, "onDestroyView");
        EventBus.getDefault().unregister(this);
    }

    //显示小红点提示
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setContacInvitedHint(ContacInvited invitedHint) {
        system_hint.setVisibility(View.VISIBLE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateExpandableListViewData(UpdateExpandableListViewData data) {
        initExpandable();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.seek:
            case R.id.linkman_friend:
                getActivity().startActivity(new Intent(getActivity(), SearchFriendActivity.class));
                break;
            case R.id.linkman_group:
                Toast.makeText(getActivity(), "点击了添加群组按钮", Toast.LENGTH_SHORT).show();
                break;
            case R.id.linkman_system_msg:
                system_hint.setVisibility(View.GONE);
                getActivity().startActivity(new Intent(getActivity(), SystemNotifycationActivity.class));
                break;

        }
    }

    //收到好友邀请提示
    public static class ContacInvited {
    }

    //更新二级列表数据
    public static class UpdateExpandableListViewData {
    }

}
